package com.yu.util;

import com.google.gson.Gson;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.BatchStatus;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.StringUtils;
import com.qiniu.util.UrlSafeBase64;
import org.apache.commons.math3.analysis.function.Min;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.BatchStatus;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.StringUtils;
import com.qiniu.util.UrlSafeBase64;
import org.apache.commons.math3.analysis.function.Min;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by taoqi on 30/03/2017.
 */
public class QiniuComponent {

    private static final Logger logger = LoggerFactory.getLogger(QiniuComponent.class);

    // TODO: 拿到七牛优惠以后，开放cdn加速URL
    public final static String CDN_URL = "http://file7niu.carmap.me/";
    public final static String NORMAL_URL = "http://onmc5rour.bkt.clouddn.com/";
    public final static String CURRENT_URL = CDN_URL;

    public final static String AccessKey = "ErPTwAHVtuy8AjtrDkVij1KlqCjKxvOvDqygJJ-Y";
    public final static String SecretKey = "rXWtqHzoh2DetQD540dJ1hqI_gX-Lx2vCDZuPmPF";
    public final static String dynamicBucket = "dynamic";

    public final static String callBackUrl = "http://file.carmap.me:9000/api/callback/qiniu";
    //public final static String callBackUrl = "http://121.40.163.108:8080/api/callback/qiniu";

    private String SysDataPath="\temp";
    private String currentBucket = dynamicBucket;
    private Configuration configuration;
    private Auth auth;

    public void setCurrentBucket(String currentBucket) {
        this.currentBucket = currentBucket;
    }

    public String geneTmpUploadToken(Long time,String resid, boolean callback) {
        StringMap putPolicy = new StringMap();
        putPolicy.put("callbackBodyType", "application/json");
        if (callback) {
            putPolicy.put("callbackUrl", callBackUrl);
        }
        putPolicy.put("callbackBody", "{\"key\":\"$(key)\",\"capturetime\":\"$(x:capturetime)\",\"imagetype\":\"$(x:imagetype)\"," +
                "\"userid\":\"$(x:userid)\",\"width\":\"$(imageInfo.width)\",\"height\":\"$(imageInfo.height)\",\"fsize\":$(fsize)," +
                "\"vwidth\":$(avinfo.video.width),\"vheight\":$(avinfo.video.height),\"vduring\":$(avinfo.video.duration)," +
                "\"lat\":\"$(x:lat)\",\"lon\":\"$(x:lon)\",\"rotate\":\"$(avinfo.video.tags.rotate)\"}");
        if (resid.endsWith(".mp4")) {
            putPolicy.putAll(getVideoThumbPolicy(resid));
        }
        return geneToken(time, putPolicy);
    }

    // 把平台已有的resid的图片，导入到七牛
//    public <Club_resources> boolean uploadFile(String resid)
//    {
//        Club_resources thisRes = club_resourcesDao.getByKey(resid);
//        if (null != thisRes && null != thisRes.getFilepath()) {
//            String filepath = thisRes.getFilepath();
//            if(!filepath.startsWith("/"))
//                filepath = "/" +filepath;
//            String fullpath = SysDataPath + filepath;
//            return uploadFileWithPath(resid, fullpath);
//        }
//        return false;
//    }

    // 把平台已有的resid+path，导入到七牛
    public boolean uploadFileWithPath(String resid, String fullpath)
    {
        if (null != resid && null != fullpath) {
            UploadManager uploadManager = getUploadManager();
            String upToken = geneTmpUploadToken(3600L,resid, true);
            try {
                Response response = uploadManager.put(fullpath, resid, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                return null != putRet.key;
            } catch (QiniuException ex) {
                return ex.code() == 579;        // 上传七牛成功，回调失败，这里不需要回调
            }

        }
        return false;
    }

    public FileInfo fetchQiniuFileInfo(String resid) {
        BucketManager bucketManager = getBucketManager();
        try {
            return bucketManager.stat(currentBucket, resid);
        } catch (QiniuException ex) {
            logger.warn("QINIU fetchQiniuFileInfo: " + ex.toString());
        }
        return null;
    }




    // private method
    public Auth getAuth() {
        if (null == auth) {
            auth = Auth.create(AccessKey, SecretKey);
        }
        return auth;
    }

    private String geneToken(long expireSeconds, StringMap policy) {
        return getAuth().uploadToken(currentBucket, null, expireSeconds, policy);
    }

    private Configuration getConfig() {
        if (null == configuration) {
            configuration = new Configuration(Zone.zone0());        // 七牛华东机房
        }
        return configuration;
    }

    private UploadManager getUploadManager() {
        return new UploadManager(getConfig());
    }

    private BucketManager getBucketManager() {
        return new BucketManager(getAuth(), getConfig());
    }

    private StringMap getVideoThumbPolicy(String resid) {
        StringMap putPolicy = new StringMap();

        resid = resid.replace(".mp4", ".jpg");
        String saveJpgEntry = String.format("%s:%s", currentBucket, resid);
        String vframeJpgFop = String.format("vframe/jpg/offset/0|saveas/%s", UrlSafeBase64.encodeToString(saveJpgEntry));

        putPolicy.put("persistentOps", vframeJpgFop);
        putPolicy.put("persistentPipeline", "chemeng-videothumb");

        return putPolicy;
    }

}
